/*
 * @(#)QueuesHolder.java
 * 2011-5-29 下午10:17:24
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.common.queue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedBlockingQueue;

import com.google.common.collect.MapMaker;

/**
 *  BlockingQueue Map的持有者.
 *  
 *  @author gxj
 *  @version 1.0
 *  @since 1.6 2011-5-29 下午10:17:24
 */
@SuppressWarnings("unchecked")
public class QueuesHolder {
	/**
	 * QueueManager注册的名称.
	 */
	public static final String QUEUEHOLDER_MBEAN_NAME = "Showcase:type=QueueManagement,name=queueHolder";

	private static ConcurrentMap<String, BlockingQueue> queueMap = new MapMaker().concurrencyLevel(32).makeMap();//消息队列

	private static int queueSize = Integer.MAX_VALUE;

	/**
	 * 根据queueName获得消息队列的静态函数.
	 * 如消息队列还不存在, 会自动进行创建.
	 */
	public static <T> BlockingQueue<T> getQueue(String queueName) {
		BlockingQueue queue = queueMap.get(queueName);

		if (queue == null) {
			BlockingQueue newQueue = new LinkedBlockingQueue(queueSize);

			//如果之前消息队列还不存在,放入新队列并返回Null.否则返回之前的值.
			queue = queueMap.putIfAbsent(queueName, newQueue);
			if (queue == null) {
				queue = newQueue;
			}
		}
		return queue;
	}

	/**
	 * 根据queueName获得消息队列中未处理消息的数量
	 */
	public static int getQueueLength(String queueName) {
		return getQueue(queueName).size();
	}

	/**
	 * 设置每个队列的最大长度, 默认为Integer最大值, 设置时不改变已创建队列的最大长度.
	 */
	public void setQueueSize(int queueSize) {
		QueuesHolder.queueSize = queueSize; //NOSONAR
	}
}